package com.infra.micro.id.domain.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.infra.common.resp.PageEx;
import com.infra.common.resp.Response;
import com.infra.common.util.ThreadPoolUtils;
import com.infra.micro.id.domain.cache.AppCache;
import com.infra.micro.id.domain.entity.IdAppPO;
import com.infra.micro.id.domain.utils.RSASignCoder;
import com.infra.micro.id.domain.repository.IdSegmentRepository;
import com.infra.micro.id.domain.repository.IdAppRepository;
import com.infra.micro.id.domain.service.IdAppService;
import com.infra.micro.id.model.req.QueryIdTokenByCondReq;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
public class IdAppServiceImpl implements IdAppService {
    @Resource
    private IdAppRepository idAppRepository;
    @Resource
    private IdSegmentRepository idSegmentRepository;
    @Resource
    protected AppCache appCache;

    @Override
    public Response<IdAppPO> queryByAppId(Integer appId) {
        IdAppPO record = idAppRepository.queryByAppId(appId);
        return record == null ? Response.error("无效ID") : Response.success(record, "查询成功");
    }

    @Override
    public Response<Integer> update(Integer appId, IdAppPO record) {
        if (appId == null || appId == 0) {
            return Response.error("无效ID");
        }
        int ret = idAppRepository.update(record);
        ThreadPoolUtils.execute(() -> {
            System.out.println("更新缓存");
        });
        return Response.success(ret, "更新成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response<Integer> insert(IdAppPO record) {
        int ret = idAppRepository.insert(record);
        idSegmentRepository.insert(record.getAppId());

        ThreadPoolUtils.execute(() -> {
            appCache.set(record.getAppId().toString(), record.getSecretKey());
            System.out.println("更新缓存完成");
        });
        return Response.success(ret, "新增成功");
    }

    @Override
    public Response<PageEx<IdAppPO, QueryIdTokenByCondReq>> queryByPage(QueryIdTokenByCondReq req) {
        PageInfo<Object> pageInfo = PageHelper.startPage(req.getPageIndex(), req.getPageSize(), StringUtils.isEmpty(req.getSortField()) ? null : req.getSortField() + " " + req.getSortType())
                .doSelectPageInfo(() -> idAppRepository.queryList(req));

        return Response.success(PageEx.builder(pageInfo, req), "查询成功");
    }

    @Override
    public Response<Boolean> refreshCache() {
        Map<String, Object> map = idAppRepository.querySimpleList().stream()
                .collect(Collectors.toMap(item -> item.getAppId().toString(), IdAppPO::getSecretKey, (a, b) -> b, ConcurrentHashMap::new));
        appCache.set(map);
        Map<Object, Object> objectObjectMap = appCache.get();
        return Response.success(true, "刷新成功");
    }

    @Override
    public Response<String> generateSecretKey() throws Exception {
        Map<String, Object> keyMap = RSASignCoder.initKey();
        byte[] privateKey = RSASignCoder.getPrivateKey(keyMap);
        keyMap.put("uuid", UUID.randomUUID().toString());
        return Response.success(RSASignCoder.sign(keyMap.get("uuid").toString(), privateKey), "签名成功");
    }
}
